<template>
  <div class="simple-login-container">
    <!-- 背景图 -->
    <div class="login-bg">
      <img :src="bgImage" alt="login background" class="bg-image" />
    </div>

    <!-- 登录表单 -->
    <div class="login-form-container">
      <div class="login-form">
        <div class="form-header">
          <h2>门户网站登录</h2>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="0"
          size="large"
        >
          <!-- 手机号输入 -->
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入用户名" @keyup.enter="getCode">
              <template #prefix>
                <img :src="mobileIcon" alt="用户名" class="custom-icon" />
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              @keyup.enter="getCode"
            >
              <template #prefix>
                <img :src="lockIcon" alt="密码" class="custom-icon" />
              </template>
            </el-input>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button :loading="loginLoading" class="login-btn" @click="getCode">
              {{ keyLoading ? '安全验证中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 验证码组件 -->
    <Verify
      ref="verify"
      :captchaType="captchaType"
      :imgSize="{ width: '360px', height: '180px' }"
      mode="pop"
      @success="handleLogin"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { setToken } from '@/utils/auth'
import * as PortalApi from '@/api/portal' // 引入门户登录API
import { SecurityApi } from '@/api/system/security' // 引入加密API
import JSEncrypt from 'jsencrypt' // 引入RSA加密库
import { Verify } from '@/components/Verifition/index' // 引入验证码组件
import bgImage from '@/assets/imgs/login/login.png'
import mobileIcon from '@/assets/imgs/login/phone.png'
import lockIcon from '@/assets/imgs/login/mima.png'

const router = useRouter()
const route = useRoute()
const loginLoading = ref(false)
const keyLoading = ref(false) // 公钥加载状态
const loginFormRef = ref()
const verify = ref()
const captchaType = ref('blockPuzzle') // 滑块验证类型
const redirect = ref<string>('')

// 加密相关
const publicKey = ref('')
const encryptor = new JSEncrypt()

// 登录表单数据
const loginForm = reactive({
  mobile: '',
  password: '',
  captchaVerification: ''
})

// 表单验证规则
const loginRules = reactive({
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
})

/** 获取RSA公钥 */
const fetchPublicKey = async () => {
  if (publicKey.value) return true // 公钥已存在则直接返回
  try {
    keyLoading.value = true
    const res = await SecurityApi.getPublicKey()
    publicKey.value = res.publicKey
    encryptor.setPublicKey(publicKey.value)
    return true
  } catch (error) {
    ElMessage.error('获取加密公钥失败，请重试')
    return false
  } finally {
    keyLoading.value = false
  }
}

/** RSA加密密码 */
const encryptPassword = (password: string) => {
  if (!publicKey.value) throw new Error('公钥不存在，无法加密')
  return encryptor.encrypt(password) || ''
}

/** 显示验证码 */
const getCode = async () => {
  try {
    // 表单验证
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    // 获取公钥
    const hasPublicKey = await fetchPublicKey()
    if (!hasPublicKey) return

    // 弹出验证码
    verify.value.show()
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请重试')
  }
}

/** 处理登录 */
const handleLogin = async (params: any) => {
  loginLoading.value = true
  try {
    // 加密密码
    const encryptedPassword = encryptPassword(loginForm.password)
    if (!encryptedPassword) {
      throw new Error('密码加密失败，请重试')
    }

    // 添加验证码验证信息
    loginForm.captchaVerification = params.captchaVerification

    // 调用门户登录API
    const loginRes = await PortalApi.portalLogin({
      username: loginForm.mobile,
      password: encryptedPassword,
      captchaVerification: loginForm.captchaVerification
    })

    if (loginRes) {
      setToken(loginRes)

      // 登录成功后跳转到指定页面或首页
      ElMessage.success('登录成功')
      router.push(redirect.value || '/')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '登录失败，请检查手机号和密码')
  } finally {
    loginLoading.value = false
  }
}

/** 初始化页面 */
onMounted(() => {
  // 获取重定向地址
  redirect.value = (route.query?.redirect as string) || ''
})
</script>

<style scoped lang="scss">
.simple-login-container {
  height: 100vh;
  width: 100vw;
  position: relative;
  overflow: hidden;

  .login-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    .bg-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .login-form-container {
    position: absolute;
    top: 50%;
    right: 15%;
    transform: translateY(-50%);

    .login-form {
      background: rgba(255, 255, 255, 0.95);
      padding: 80px;
      border-radius: 8px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      min-width: 500px;

      .custom-icon {
        width: 14px;
      }

      .form-header {
        text-align: center;
        margin-bottom: 30px;

        h2 {
          color: #333;
          font-size: 24px;
          font-weight: 600;
          margin: 0;
        }
      }

      .login-btn {
        width: 100%;
        height: 45px;
        font-size: 16px;
        margin-top: 60px;
        background-color: #1778ff;
        color: #fdfeff;
      }
    }
  }
}
</style>
